#include <iostream>
#include <stdlib.h>
#include <stdlib.h>
#include <unistd.h>
#include <string>

bool GetQueryString(std::string &query_string)
{
  std::string method = getenv("METHOD_ENV");
  if (method == "GET")
  {
    std::cerr << "Debug Query_string: " << getenv("QUERY_STRING") << std::endl;
    query_string = getenv("QUERY_STRING");
    return true;
  }
  else if (method == "POST")
  {
    int content_length = atoi(getenv("CONTENT_LENGTH"));
    char ch = 0;
    while (content_length--)
    {
      read(0, &ch, 1);
      query_string.push_back(ch);
    }
    return true;
  }
  return false;
}

bool CutString(std::string &target, std::string &key_out, std::string &value_out, std::string sep)
{
  size_t pos = target.find(sep);
  if (pos != std::string::npos)
  {
    key_out = target.substr(0, pos);
    value_out = target.substr(pos + sep.size());
    return true;
  }
  return false;
}

int main()
{
  std::string query_string;
  GetQueryString(query_string);

  std::string str1;
  std::string str2;
  CutString(query_string, str1, str2, "&");

  std::string name1;
  std::string value1;
  CutString(str1, name1, value1, "=");

  std::string name2;
  std::string value2;
  CutString(str2, name2, value2, "=");

  int x = atoi(value1.c_str());
  int y = atoi(value2.c_str());
  std::cout << "<html>";
  std::cout << "<head><meta charset=\"utf -8\"></head>";
  std::cout << "<body>";
  std::cout << "<h3>" << value1 << " + " << value2 << " = " << x + y << "</h3>";
  std::cout << "<h3>" << value1 << " - " << value2 << " = " << x - y << "</h3>";
  std::cout << "<h3>" << value1 << " * " << value2 << " = " << x * y << "</h3>";
  std::cout << "<h3>" << value1 << " / " << value2 << " = " << x / y << "</h3>";
  std::cout << "</body>";
  std::cout << "</html>";
  return 0;
}
